/**
 * @author Rid King
 * @since 2017-05-02
 * @version 0.0.0
 * @description 观察者
 */
'user strict';

import Observer from './observer.js'

class _Observable {
    /**
     * @description 构造函数
     * @param producer <Function> 数据生产函数
    */
    constructor (producer) {
        this._producer = producer
    }

    /**
     * @description 订阅
     * @param observer <Function/Observer> 成功回调/消费者
     * @param error <Function> 失败回调
     * @param complete <Function> 结束回调
     * @return <Function> 取消订阅
    */
    subscribe (observer, error, complete) {
        let _observer = null
        // 直接取
        if (observer instanceof Observer) {
            _observer = observer
        }
        // 生成订阅者对象
        else {
            _observer = new Observer(observer, error, complete)
        }

        // 取消订阅回调
        _observer.unsub = this._producer(_observer)

        // 返回订阅者取消订阅函数闭包
        return (function (obser, unsub) {
            return function () {
                unsub.apply(obser, arguments)
            }
        })(_observer, _observer.unsubscribe)
    }
}

export default _Observable